<?php
/*
 * @Description: 
 * @Author: Karis
 * @Date: 2022-02-22 03:08:09
 * @LastEditors: Terry
 * @LastEditTime: 2022-03-08 17:51:45
 * @FilePath: \tp6\app\openApi\command\ButtElectricData.php
 */
declare (strict_types = 1);
namespace app\openApi\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class ButtElectricData extends Command{
    protected function configure()
    {
        // 指令配置
        $this->setname('app\openApi\command\buttElectricData')
            ->setDescription('发送电表设备详细数据');
    }
    
    //提交数据
    protected function execute(Input $input, Output $output){
        $this->getElectricData();
        \Swoole\timer::tick(30*1000, function () use ($output){
            $url = 'https://demoapi.auxface.com/api/openApi/official/v1/electric/upload';
            $appid='AUXb2fff94b065f51a';
            $secret='idfm7tcfq0cvo2bf8t7gnkml1aw7gh';
            $timestamp = time();
            $electricData = $this->getElectricData();
            $data = [
                'appId'=>$appid,
                'timestamp'=>(string)$timestamp,
                'data'=>$electricData,
            ];
            $data['sign']=$this->getSign($data,$secret);
            $result = $this->curl_request($url,json_encode($data));
            if(!$result['code'] == 0) return $output->writeln($result['message']);
            return $result;
        });
    }

    //随机数据
    private function getElectricData(){
        $electricData['usingCount'] = random_int(0,30).'.'.random_int(0,9).random_int(0,9);
        $electricData['code'] = '123213';
        return $electricData;
    }
    //签名文件
    private function getSign($data,$secret){
        $data['data'] = json_encode($data);
        $sign = "appId=".$data['appId']."&appSecret=".$secret."&data=".$data['data']."&timestamp=".$data['timestamp'];
        $sign = strtolower($sign);
        return md5($sign);
    }
    // CURL
    function curl_request($url,$data = null){
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        $output = curl_exec($curl);
        curl_close($curl);
        $res = json_decode($output,true);
        return $res;
        }
}
